package name.ekr.edu.threads.chatserver.server;

import static name.ekr.edu.threads.chatserver.Constants.PORT;

import java.io.Closeable;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class Acceptor implements Closeable {
	private static Logger logger = LoggerFactory.getLogger(Acceptor.class);
	private int port;
	private ServerSocket serverSocket = null;
	
	public Acceptor(int port) {
		this.port = port;
		try {
			serverSocket = new ServerSocket(PORT);
			logger.info("Port opened at " + serverSocket.getInetAddress());
		} catch (IOException e) {
			logger.error("", e);
			throw new RuntimeException("Can't open port");
		}
	}

	public Connection accept() {
		try {
			Socket socket = serverSocket.accept();
			Connection connection = new Connection(socket);
			logger.info("Connected client " + socket.getInetAddress());
			return connection;
		} catch (IOException e) {
			logger.error("", e);
			throw new RuntimeException("Can't get connection from client");
		}
	}
	
	@Override
	public void close() {
		try {
			serverSocket.close();
			logger.info("Port closed");
		} catch (IOException e) {
			logger.error("", e);
			throw new RuntimeException("Can't close port");
		}
	}
}
